<template>
  <div class="create-picture">
    <a-card :bordered="false" class="main-card">
      <div class="page-header">
        <h2>创建图片</h2>
      </div>

      <!-- 本地上传 -->
      <div class="upload-section">
        <a-upload-dragger
          v-model:fileList="fileList"
          :beforeUpload="beforeUpload"
          :showUploadList="false"
          multiple
          accept="image/*"
        >
          <p class="ant-upload-drag-icon">
            <InboxOutlined />
          </p>
          <p class="ant-upload-text">点击或拖拽图片到此区域上传</p>
          <p class="ant-upload-hint">
            支持单个或批量上传，每张图片不超过5MB
          </p>
        </a-upload-dragger>
      </div>

      <!-- 预览和信息编辑区域 -->
      <div v-if="previewList.length > 0" class="preview-section">
        <h3>待上传图片 ({{ previewList.length }})</h3>

        <!-- 批量设置开关 -->
        <div class="batch-settings">
          <a-switch
            v-model:checked="useBatchSettings"
            checked-children="统一设置"
            un-checked-children="单独设置"
          />
        </div>

        <!-- 批量设置表单 -->
        <div v-if="useBatchSettings" class="batch-form">
          <a-form layout="vertical">
            <a-form-item label="文件名前缀">
              <a-input
                v-model:value="batchSettings.prefix"
                placeholder="请输入文件名前缀"
                @change="applyBatchSettings('prefix')"
              />
            </a-form-item>
            <a-form-item label="描述">
              <a-textarea
                v-model:value="batchSettings.description"
                placeholder="请输入图片描述"
                :rows="2"
                @change="applyBatchSettings('description')"
              />
            </a-form-item>
            <a-form-item label="分类">
              <a-select
                v-model:value="batchSettings.category"
                placeholder="请选择分类"
                style="width: 100%"
                @change="applyBatchSettings('category')"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="category in categories"
                  :key="category"
                  :value="category"
                >
                  {{ category }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item label="标签（可多选，最多4个）">
              <a-select
                v-model:value="batchSettings.tags"
                mode="multiple"
                placeholder="请选择标签"
                style="width: 100%"
                @change="(tags) => handleTagsChange(tags, 'batchSettings')"
                :getPopupContainer="(triggerNode) => triggerNode.parentNode"
              >
                <a-select-option
                  v-for="tag in tags"
                  :key="tag"
                  :value="tag"
                >
                  {{ tag }}
                </a-select-option>
              </a-select>
            </a-form-item>
            <a-form-item>
              <a-switch
                v-model:checked="batchSettings.isPublic"
                checked-children="公开"
                un-checked-children="私密"
                @change="applyBatchSettings('isPublic')"
              />
            </a-form-item>
          </a-form>
        </div>

        <div class="preview-list">
          <div
            v-for="(item, index) in previewList"
            :key="index"
            class="preview-item"
          >
            <!-- 预览 -->
            <div class="preview-image">
              <template v-if="item.type === 'image'">
                <img :src="item.preview" :alt="item.fileName" />
              </template>
              <template v-else>
                <video :src="item.preview" controls></video>
                <div class="media-info" v-if="item.duration">
                  时长: {{ formatDuration(item.duration) }}
                  <template v-if="item.resolution">
                    | {{ item.resolution.width }}×{{ item.resolution.height }}
                  </template>
                </div>
              </template>
              <div class="preview-actions">
                <a-button
                  type="text"
                  danger
                  @click="removePreview(index)"
                >
                  <template #icon><DeleteOutlined /></template>
                </a-button>
              </div>
            </div>

            <!-- 图片信息表单 -->
            <div v-if="!useBatchSettings" class="image-form">
              <a-form layout="vertical">
                <a-form-item label="文件名">
                  <a-input
                    v-model:value="item.fileName"
                    placeholder="请输入文件名"
                  />
                </a-form-item>
                <a-form-item label="描述">
                  <a-textarea
                    v-model:value="item.description"
                    placeholder="请输入图片描述"
                    :rows="2"
                  />
                </a-form-item>
                <a-form-item label="分类">
                  <a-select
                    v-model:value="item.category"
                    placeholder="请选择分类"
                    style="width: 100%"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="category in categories"
                      :key="category"
                      :value="category"
                    >
                      {{ category }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item label="标签（可多选，最多4个）">
                  <a-select
                    v-model:value="item.tags"
                    mode="multiple"
                    placeholder="请选择标签"
                    style="width: 100%"
                    @change="(tags) => handleTagsChange(tags, 'item', index)"
                    :getPopupContainer="(triggerNode) => triggerNode.parentNode"
                  >
                    <a-select-option
                      v-for="tag in tags"
                      :key="tag"
                      :value="tag"
                    >
                      {{ tag }}
                    </a-select-option>
                  </a-select>
                </a-form-item>
                <a-form-item>
                  <a-switch
                    v-model:checked="item.isPublic"
                    checked-children="公开"
                    un-checked-children="私密"
                  />
                </a-form-item>
              </a-form>
            </div>
          </div>
        </div>

        <!-- 批量操作区 -->
        <div class="batch-actions">
          <a-space>
            <a-button @click="clearAll">
              <template #icon><ClearOutlined /></template>
              清空
            </a-button>
            <a-button
              type="primary"
              @click="handleUpload"
              :loading="uploading"
            >
              <template #icon><CloudUploadOutlined /></template>
              开始上传
            </a-button>
          </a-space>
        </div>
      </div>
    </a-card>
  </div>

  <!-- 添加进度显示，改为固定位置的小窗口 -->
  <div v-if="isProcessing" class="processing-status">
    <div class="processing-content">
      <Progress type="circle" :percent="processingProgress" :size="60" />
      <div class="processing-text">
        正在处理图片 ({{ processedCount }}/{{ totalImages }})
      </div>
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, nextTick } from 'vue'
import { message, Progress } from 'ant-design-vue'
import { useRouter, useRoute } from 'vue-router'
import {
  InboxOutlined,
  LeftOutlined,
  DeleteOutlined,
  ClearOutlined,
  CloudUploadOutlined
} from '@ant-design/icons-vue'
import {
  uploadImagesUsingPost1,
  getCategoriesUsingGet1,
  getTagsUsingGet1
} from '@/api/tupianguanlijiekou'

const router = useRouter()
const route = useRoute()

// 文件列表
const fileList = ref<any[]>([])
const previewList = ref<any[]>([])

// 加载状态
const uploading = ref(false)

// 分类和标签
const categories = ref<string[]>([])
const tags = ref<string[]>([])

// 批量设置相关
const useBatchSettings = ref(false)
const batchSettings = ref({
  prefix: '',
  description: '',
  category: undefined,
  tags: [] as string[],
  isPublic: true
})

const processingProgress = ref(0)
const isProcessing = ref(false)
const totalImages = ref(0)
const processedCount = ref(0)

// 应用批量设置
const applyBatchSettings = (field: string) => {
  previewList.value.forEach(item => {
    item[field] = batchSettings.value[field]
  })
}

// 获取分类列表
const fetchCategories = async () => {
  try {
    const res = await getCategoriesUsingGet1()
    if (res.data.code === 200) {
      categories.value = res.data.data
    }
  } catch (error) {
    console.error('获取分类失败:', error)
  }
}

// 获取标签列表
const fetchTags = async () => {
  try {
    const res = await getTagsUsingGet1()
    if (res.data.code === 200) {
      tags.value = res.data.data
    }
  } catch (error) {
    console.error('获取标签失败:', error)
  }
}

// 格式化时长
const formatDuration = (seconds: number) => {
  const minutes = Math.floor(seconds / 60)
  const remainingSeconds = Math.floor(seconds % 60)
  return `${minutes}:${remainingSeconds.toString().padStart(2, '0')}`
}

// 本地上传前处理
const beforeUpload = (file: File) => {
  // 检查文件类型
  const isValidType = file.type.startsWith('image/')

  if (!isValidType) {
    message.error(`只能上传图片文件!`)
    return false
  }

  // 检查文件大小
  const maxSize = 5 // MB
  const isWithinSizeLimit = file.size / 1024 / 1024 < maxSize
  if (!isWithinSizeLimit) {
    message.error(`图片必须小于${maxSize}MB!`)
    return false
  }

  // 创建预览
  const reader = new FileReader()

  reader.readAsDataURL(file)
  reader.onload = () => {
    previewList.value.push({
      type: 'image',
      file,
      fileName: file.name.substring(0, file.name.lastIndexOf('.')),
      preview: reader.result,
      description: '',
      category: undefined,
      tags: [],
      isPublic: true
    })
  }

  return false // 阻止自动上传
}

// 移除预览图片
const removePreview = (index: number) => {
  previewList.value.splice(index, 1)
}

// 清空所有
const clearAll = () => {
  previewList.value = []
  fileList.value = []
}

// 处理上传
const handleUpload = async () => {
  if (previewList.value.length === 0) {
    message.warning('请先添加图片')
    return
  }

  uploading.value = true
  try {
    const formData = new FormData()

    previewList.value.forEach(item => {
      formData.append('files', item.file)
    })

    const params = {
      prefix: useBatchSettings.value ? batchSettings.value.prefix : previewList.value[0].fileName,
      category: useBatchSettings.value ? batchSettings.value.category : previewList.value[0].category,
      description: useBatchSettings.value ? batchSettings.value.description : previewList.value[0].description,
      isPublic: useBatchSettings.value ? (batchSettings.value.isPublic ? 1 : 0) : (previewList.value[0].isPublic ? 1 : 0)
    }

    // 把标签作为一个数组参数
    const tags = useBatchSettings.value ? batchSettings.value.tags : previewList.value[0].tags
    formData.append('tags', JSON.stringify(tags))

    // 添加其他参数
    Object.keys(params).forEach(key => {
      if (params[key] !== undefined) {
        formData.append(key, params[key])
      }
    })

    // 本地文件上传
    const res = await uploadImagesUsingPost1({
      timeout: 60000  // 将超时时间设置为60秒
    }, formData)
    if (res.data.code === 200) {
      message.success('上传成功')
      clearAll()
    } else {
      message.error(res.data.message || '上传失败')
    }
  } catch (error: any) {
    message.error(error.message || '上传失败')
  } finally {
    uploading.value = false
  }
}

// 分批处理图片
const processImagesInBatches = async () => {
  const BATCH_SIZE = 3 // 每批处理的图片数量

  try {
    const uploadData = sessionStorage.getItem('unsplashPendingImages')
    if (!uploadData) return

    const imageInfos = JSON.parse(uploadData)
    totalImages.value = imageInfos.length
    isProcessing.value = true

    // 分批处理
    for (let i = 0; i < imageInfos.length; i += BATCH_SIZE) {
      const batch = imageInfos.slice(i, i + BATCH_SIZE)

      await Promise.all(batch.map(async (imageInfo) => {
        try {
          // 下载图片
          const response = await fetch(imageInfo.url)
          const blob = await response.blob()
          const file = new File([blob], `unsplash_${imageInfo.id}.jpg`, { type: 'image/jpeg' })

          // 创建预览
          const reader = new FileReader()
          await new Promise((resolve) => {
            reader.onload = () => {
              previewList.value.push({
                file,
                fileName: `unsplash_${imageInfo.id}.jpg`,
                preview: reader.result,
                description: imageInfo.description,
                authorName: imageInfo.authorName,
                originalUrl: imageInfo.url,
                tags: imageInfo.tags,
                category: undefined,
                isPublic: true
              })
              resolve(null)
            }
            reader.readAsDataURL(blob)
          })

          // 更新进度
          processedCount.value++
          processingProgress.value = Math.round((processedCount.value / totalImages.value) * 100)
        } catch (error) {
          console.error('处理图片失败:', error)
          message.error(`处理图片 ${imageInfo.id} 失败`)
        }
      }))

      // 每批处理完后稍作延迟，避免浏览器过载
      await new Promise(resolve => setTimeout(resolve, 500))
    }

    // 清理 sessionStorage
    sessionStorage.removeItem('unsplashPendingImages')
    message.success('所有图片处理完成')
  } catch (error) {
    console.error('批量处理图片失败:', error)
    message.error('批量处理图片失败')
  } finally {
    isProcessing.value = false
  }
}

// 添加标签选择限制处理函数
const handleTagsChange = (selectedTags: string[], field: 'batchSettings' | 'item', index?: number) => {
  const tags = selectedTags || []
  if (tags.length > 4) {
    // 只保留最后4个选中的标签
    const limitedTags = tags.slice(-4)
    if (field === 'batchSettings') {
      batchSettings.value.tags = limitedTags
      if (useBatchSettings.value) {
        applyBatchSettings('tags')
      }
    } else if (index !== undefined) {
      previewList.value[index].tags = limitedTags
    }
  }
}

onMounted(async () => {
  if (route.query.from === 'unsplash') {
    processImagesInBatches()
  }

  // 原有的初始化代码
  await fetchCategories()
  await fetchTags()
})

defineExpose({
  handleTagsChange,
})
</script>

<style scoped>
.create-picture {
  padding: 24px;
  background: var(--theme-background);
  min-height: calc(100vh - 64px);
  transition: all 0.3s ease;
}

.main-card {
  background: var(--theme-surface);
  border-radius: 8px;
  border: 1px solid var(--theme-border);
  box-shadow: 0 2px 8px var(--theme-shadow);
}

.page-header {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
  position: relative;
}

.page-header h2 {
  flex: 1;
  text-align: center;
  margin: 0;
  font-size: 24px;
  font-weight: 500;
  color: var(--theme-text);
}


.upload-section {
  margin-bottom: 24px;
}

/* 上传区域主题适配 */
:deep(.ant-upload-drag) {
  background: var(--theme-surface);
  border: 2px dashed var(--theme-border);
  border-radius: 8px;
  transition: all 0.3s ease;
}

:deep(.ant-upload-drag:hover) {
  border-color: var(--theme-primary);
}

:deep(.ant-upload-drag.ant-upload-drag-hover) {
  border-color: var(--theme-primary);
  background: var(--theme-background);
}

:deep(.ant-upload-drag .ant-upload-drag-icon) {
  color: var(--theme-primary);
  font-size: 48px;
  margin-bottom: 16px;
}

:deep(.ant-upload-drag .ant-upload-text) {
  color: var(--theme-text) !important;
  font-size: 18px !important;
  font-weight: 600 !important;
  margin-bottom: 12px !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

:deep(.ant-upload-drag .ant-upload-hint) {
  color: var(--theme-textSecondary) !important;
  font-size: 16px !important;
  font-weight: 500 !important;
  line-height: 1.5 !important;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.1) !important;
}

/* 深色主题下的文字增强 */
[data-theme="dark"] :deep(.ant-upload-drag .ant-upload-text) {
  color: #ffffff !important;
  text-shadow: 0 2px 4px rgba(0, 0, 0, 0.5) !important;
  font-weight: 700 !important;
}

[data-theme="dark"] :deep(.ant-upload-drag .ant-upload-hint) {
  color: #e0e0e0 !important;
  text-shadow: 0 1px 3px rgba(0, 0, 0, 0.4) !important;
  font-weight: 600 !important;
}

/* 浅色主题下的文字增强 */
[data-theme="light"] :deep(.ant-upload-drag .ant-upload-text) {
  color: #333333 !important;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.8) !important;
  font-weight: 600 !important;
}

[data-theme="light"] :deep(.ant-upload-drag .ant-upload-hint) {
  color: #666666 !important;
  text-shadow: 0 1px 2px rgba(255, 255, 255, 0.6) !important;
  font-weight: 500 !important;
}

.preview-section {
  margin-top: 32px;
}

.preview-section h3 {
  margin-bottom: 16px;
  color: var(--theme-text);
  font-weight: 600;
}

.preview-list {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
  gap: 16px;
  margin-top: 16px;
}

.preview-item {
  border: 1px solid var(--theme-border);
  border-radius: 4px;
  overflow: hidden;
  background: var(--theme-surface);
  transition: all 0.3s ease;
}

.preview-item:hover {
  border-color: var(--theme-primary);
  box-shadow: 0 4px 12px var(--theme-shadow);
}

.preview-image {
  position: relative;
  padding-top: 100%;
  background: var(--theme-background);
  overflow: hidden;
}

.preview-image img,
.preview-image video {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  object-fit: cover;
}

.preview-actions {
  position: absolute;
  top: 8px;
  right: 8px;
  z-index: 2;
}

.media-info {
  position: absolute;
  bottom: 0;
  left: 0;
  right: 0;
  background: rgba(0, 0, 0, 0.7);
  color: white;
  padding: 8px;
  font-size: 12px;
}

.preview-content {
  padding: 16px;
}

.preview-content h4 {
  margin: 0 0 8px 0;
  color: var(--theme-text);
  font-weight: 500;
}

.preview-content p {
  margin: 0 0 4px 0;
  color: var(--theme-textSecondary);
  font-size: 12px;
}

/* 表单主题适配 */
:deep(.ant-form-item-label > label) {
  color: var(--theme-text) !important;
  font-weight: 500;
}

:deep(.ant-input) {
  background: var(--theme-surface) !important;
  border-color: var(--theme-border) !important;
  color: var(--theme-text) !important;
}

:deep(.ant-input:focus),
:deep(.ant-input-focused) {
  border-color: var(--theme-primary) !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

:deep(.ant-input::placeholder) {
  color: var(--theme-textSecondary) !important;
}

:deep(.ant-textarea) {
  background: var(--theme-surface) !important;
  border-color: var(--theme-border) !important;
  color: var(--theme-text) !important;
}

:deep(.ant-textarea:focus),
:deep(.ant-textarea-focused) {
  border-color: var(--theme-primary) !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

:deep(.ant-select) {
  background: var(--theme-surface) !important;
}

:deep(.ant-select-selector) {
  background: var(--theme-surface) !important;
  border-color: var(--theme-border) !important;
  color: var(--theme-text) !important;
}

:deep(.ant-select-focused .ant-select-selector) {
  border-color: var(--theme-primary) !important;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2) !important;
}

:deep(.ant-select-selection-item) {
  color: var(--theme-text) !important;
}

/* 修复下拉列表跟随问题 */
:deep(.ant-select-dropdown) {
  position: absolute !important;
  top: 100% !important;
  left: 0 !important;
  right: 0 !important;
  z-index: 1050 !important;
  background: var(--theme-surface) !important;
  border: 1px solid var(--theme-border) !important;
  border-radius: 6px !important;
  box-shadow: 0 4px 12px var(--theme-shadow) !important;
  margin-top: 4px !important;
}

:deep(.ant-select-dropdown .ant-select-item) {
  color: var(--theme-text) !important;
  background: var(--theme-surface) !important;
  padding: 8px 12px !important;
  transition: all 0.3s ease !important;
}

:deep(.ant-select-dropdown .ant-select-item:hover) {
  background: var(--theme-background) !important;
  color: var(--theme-primary) !important;
}

:deep(.ant-select-dropdown .ant-select-item-option-selected) {
  background: var(--theme-primary) !important;
  color: white !important;
}

:deep(.ant-select-dropdown .ant-select-item-option-active) {
  background: var(--theme-background) !important;
  color: var(--theme-primary) !important;
}

:deep(.ant-switch) {
  background: var(--theme-border) !important;
}

:deep(.ant-switch-checked) {
  background: var(--theme-primary) !important;
}

/* 按钮主题适配 */
:deep(.ant-btn) {
  border-radius: 6px;
  transition: all 0.3s ease;
}

:deep(.ant-btn-primary) {
  background: var(--theme-primary);
  border-color: var(--theme-primary);
  color: white;
}

:deep(.ant-btn-primary:hover) {
  background: var(--theme-secondary);
  border-color: var(--theme-secondary);
}

:deep(.ant-btn-default) {
  background: var(--theme-surface);
  border-color: var(--theme-border);
  color: var(--theme-text);
}

:deep(.ant-btn-default:hover) {
  border-color: var(--theme-primary);
  color: var(--theme-primary);
}

/* 处理状态窗口 */
.processing-status {
  position: fixed;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  z-index: 1000;
  background: var(--theme-surface);
  border: 1px solid var(--theme-border);
  border-radius: 8px;
  padding: 24px;
  box-shadow: 0 8px 24px var(--theme-shadow);
}

.processing-content {
  text-align: center;
}

.processing-text {
  margin-top: 16px;
  color: var(--theme-text);
  font-size: 14px;
  font-weight: 500;
}

/* 批量设置区域 */
.batch-settings {
  margin-bottom: 16px;
  padding: 16px;
  background: var(--theme-background);
  border: 1px solid var(--theme-border);
  border-radius: 6px;
}

.batch-form {
  margin-top: 16px;
}

.batch-actions {
  margin-top: 24px;
  text-align: center;
}
</style>
